#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include <stdio.h>
#include <stdlib.h>

int sdl_error()
{
	printf("SDL error %s\n", SDL_GetError());
	return 1;
}

int sdl_print_bpp()
{
	const SDL_VideoInfo* vi;
	const SDL_PixelFormat* pf;
	vi = SDL_GetVideoInfo();
	if(!vi)
		sdl_error();
	pf = vi->vfmt;
	printf("we need bpp 32, check what we have\n");
	printf("bpp %d\n", pf->BitsPerPixel);
	return 1;
}

int sdl_preset_opengl()
{
	if(SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8))
		sdl_error();
    if(SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8))
    	sdl_error();
    if(SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8))
    	sdl_error();
    if(SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16))
    	sdl_error();
    if(SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1))
    	sdl_error();
    return 1;
}

int sdl_create_window()
{
	if(SDL_Init(SDL_INIT_VIDEO))
		sdl_error();
	sdl_print_bpp();
	sdl_preset_opengl();
    if (!SDL_SetVideoMode(800, 600, 32, SDL_OPENGL 
		| SDL_NOFRAME))
    	sdl_error();
	return 1;
}

int gl_print_error()
{
    GLenum error;
    error = glGetError();
    if (error == GL_NO_ERROR) {
        return 0;
    }
    printf("%s", glGetString(error));
    return 1;
}

int gl_init()
{	
	glClearDepth(1.0f);
	glDepthFunc(GL_LESS);               
    glEnable(GL_DEPTH_TEST); 
	glClearColor(0.0f, 1.0f, 0.0f, 0.0f);
	glColor3f(1.0f, 0.0f, 0.0f);
	glShadeModel(GL_SMOOTH);                     
	glViewport(0, 0, 800, 600);
	glMatrixMode(GL_PROJECTION); 
    gluPerspective(45.0f, (float)800/(float)600, 0.1f, 100.0f);                           
    glMatrixMode(GL_MODELVIEW);
	return 1;   
}

int init()
{
	sdl_create_window();
	gl_init();
	return 1;
}

int process_events()
{
	SDL_Event event;
	while(SDL_PollEvent(&event))
	{
		switch(event.type) 
    	{
    		// exit on escape
    		case SDL_KEYDOWN:
    			if(event.key.keysym.sym == SDLK_ESCAPE)
    			{
     				SDL_Quit();
     				return 0;
     			}
     			break;
     		// exit on window close button
     		case SDL_QUIT:
     			return 0;
    	}
    	
 	}
 	return 1;
}

int draw()
{
	 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	 glLoadIdentity();
	 glTranslatef(-0.0f, 0.0f, -3.0f);
	 glBegin(GL_TRIANGLES);
	 glVertex3f(0.0f, 1.0f, 0.0f); 
     glVertex3f(-1.0f, -1.0f, 0.0f); 
     glVertex3f(1.0f, -1.0f, 0.0f);
	 glEnd(); 
	 SDL_GL_SwapBuffers();
	 gl_print_error();
	 return 1;
}

int main()
{
	init();
	while(process_events()) 
	{
    	draw();
    }
	return 0;
}
